import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  GetAllfinancingSupplyChainFinanceSettlementBeenSubmitted,
  ApplyPaymentSettlementUpdatePaymentStatus,
  ApplyPaymentSettlementUpdateRouteType,
  FinancialTransactionsUsersGetByUsername,
  TransactionsOredrsCreate,
  ApplyPaymentSettlementUpdateIsSettlement,
  ApplyPaymentSettlementCaltucate
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
import { emitter } from "@/utils/mitt";
export function useFincilaLending() {
  const route = useRoute()
  const dataList = ref<any>([]);
  const loading = ref<boolean>(false);
  const DialogVisible = ref<boolean>(false);
  const rowData = ref()
  const selectData = ref()
  const selectType = ref()
  const selectRouteTypeVisible = ref(false)
  const routerTittle = ref()
  const lenderVisible = ref(false)
  const payBalanceVisible = ref(false)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "额度核定申请编号",
      prop: "financingLineApprovalApplicationNumber",
      width: 135
    },
    {
      label: "企业名称",
      prop: "supplyName",
      minWidth: 150
    },
    {
      label: "采购项目",
      prop: "purchaseName",
    },
    {
      label: "应收账款总金额（元）",
      prop: "accountReceivableAmount",
      width: 140
    },
    {
      label: "信用评级",
      prop: "creditRating",
      width: 80
    },
    {
      label: "融资率",
      prop: "financingInterestRate",
      width: 75
    },
    {
      label: "融资额度（元）",
      prop: "financingLine",
    },
    {
      label: "融资利率",
      prop: "financingRate",
      width: 80
    },
    {
      label: "融资金额（元）",
      prop: "financingAmount",
    },
    {
      label: "放款模式",
      prop: "routeType",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.routeType == 1 ? "success" : row.routeType == 2 ? "" : "error"}>
          {
            row.routeType == 1 ? "自有资金放款" : row.routeType == 2 ? "资产证券化" : '未处理'
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
      width: 320
    }
  ];

  const payData = reactive({
    totalReceivables: '',
    loanInterest: '',
    remainingBalance: ''
  })


  async function getSupplierEnterpriseInfoGetAllByPagedAndSort() {
    const res = await GetAllfinancingSupplyChainFinanceSettlementBeenSubmitted({
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      type: '',
      taskId: route.query.taskId,
      planId: route.query.planId
    });
    if (res.success) {
      res.data.items.forEach((item) => {
        item.purchaseName = item.purchaseName.split(";").join(",").replace(/^,/, "");
      })
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }


  async function handleApply(row, type) {
    selectData.value = row
    selectType.value = type
    // 资产证券化就是直接放款  组建资产池是后面放款
    if (type == 1) {
      routerTittle.value = `是否确认向 ${row.supplyName}企业发放融资金额${row.financingAmount}元?`
      selectRouteTypeVisible.value = true
    } else {
      if (Number(row.financingAmount) < 1000000) {
        ElMessage.warning('融资金额需大于一百万才可以进行资产证券化')
      } else {
        routerTittle.value = '是否确认发起资产证券化项目?'
        selectRouteTypeVisible.value = true
      }
    }
  }

  function handleLender(row) {
    selectData.value = row
    routerTittle.value = `是否确认向 ${row.supplyName}企业发放融资金额${row.financingAmount} 元 ? `
    lenderVisible.value = true
  }


  async function saveApply() {
    if (selectType.value == 1) {
      //转账
      const success = await tresferToSupplier(selectData.value)
      if (success) {
        //修改状态 当前是自有资金 直接改成已放款
        const data = qs.stringify({
          id: selectData.value.applyPaymentSettlementId,
          status: 2,
        });
        const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
        //增加queryType
        const data1 = qs.stringify({
          id: selectData.value.applyPaymentSettlementId,
          routeType: 1,
        });
        const res1 = await ApplyPaymentSettlementUpdateRouteType(data1)
        getSupplierEnterpriseInfoGetAllByPagedAndSort()
        selectRouteTypeVisible.value = false
      }
    } else {
      const data = qs.stringify({
        id: selectData.value.applyPaymentSettlementId,
        status: 1,
      });
      const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
      if (res.success) {
      } else {
        ElMessage.error(res.msg)
      }
      //增加queryType
      const data1 = qs.stringify({
        id: selectData.value.applyPaymentSettlementId,
        routeType: 2,
      });
      selectRouteTypeVisible.value = false
      const res1 = await ApplyPaymentSettlementUpdateRouteType(data1)
      if (res1.success) {
        ElMessage.success('组建资产证券化成功')
      } else {
        ElMessage.error(res1.msg)
      }
      getSupplierEnterpriseInfoGetAllByPagedAndSort()
    }
  }

  async function handelSupplierPay() {
    //转账
    const success = await tresferToSupplier(selectData.value)
    //修改状态 当前是自有资金 直接改成已放款
    if (success) {
      const data = qs.stringify({
        id: selectData.value.applyPaymentSettlementId,
        status: 3,
      });
      const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
      if (res.success) {
        lenderVisible.value = false
        getSupplierEnterpriseInfoGetAllByPagedAndSort()
      } else {
        ElMessage.error(res.msg)
      }
    }
  }


  async function tresferToSupplier(row) {
    const data = qs.stringify({
      userName: '金融公司',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res = await FinancialTransactionsUsersGetByUsername(data)
    if (Number(res.data.balance) == 0) {
      ElMessage.warning('金融公司的钱包余额为0元，请先充值！！！')
      return false
    }
    const fromTransactionsUserId = res.data.transactionsUserId
    const data1 = qs.stringify({
      userName: '供应商企业',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res1 = await FinancialTransactionsUsersGetByUsername(data1)
    const toTransactionsUserId = res1.data.transactionsUserId
    const data2 = {
      fromTransactionsUserId: fromTransactionsUserId,
      toTransactionsUserId: toTransactionsUserId,
      menuId: '',
      amount: row.financingAmount,
      description: '金融公司支付融资金额',
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res2 = await TransactionsOredrsCreate(data2)
    if (res2.success) {
      ElMessage.success('完成供应商放款！')
      emitter.emit('refreshMoney')
      return true;
    } else {
      ElMessage.error(res2.msg)
      return false;
    }
  }

  async function handlePayData(row) {
    selectData.value = row
    const data1 = qs.stringify({
      applyPaymentSettlementId: row.applyPaymentSettlementId
    })
    let res = await ApplyPaymentSettlementCaltucate(data1)
    if (res.success) {
      payData.totalReceivables = res.data.totalReceivables
      payData.loanInterest = res.data.loanInterest
      payData.remainingBalance = res.data.remainingBalance
      routerTittle.value = `供应商企业贷款本息一共${payData.loanInterest} 元，应收账款总额为${payData.totalReceivables} 元，是否确定向供应商企业支付应收账款余额${payData.remainingBalance} 元 ? `
      payBalanceVisible.value = true
    } else {
      ElMessage.error(res.msg)
    }
  }
  //支付余额
  async function payLeaveMoney() {
    const data = qs.stringify({
      userName: '金融公司',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res1 = await FinancialTransactionsUsersGetByUsername(data)
    if (Number(res1.data.balance) == 0) {
      ElMessage.warning('金融公司的钱包余额为0元，请先充值！！！')
      return
    }
    const fromTransactionsUserId = res1.data.transactionsUserId
    const data1 = qs.stringify({
      userName: '供应商企业',
      taskId: route.query.taskId,
      planId: route.query.planId,
    })
    let res2 = await FinancialTransactionsUsersGetByUsername(data1)
    const toTransactionsUserId = res2.data.transactionsUserId
    const data2 = {
      fromTransactionsUserId: fromTransactionsUserId,
      toTransactionsUserId: toTransactionsUserId,
      menuId: '',
      amount: payData.remainingBalance,
      description: '金融公司支付余额',
      taskId: route.query.taskId,
      planId: route.query.planId,
      purchaseOrderId: selectData.value.purchaseOrderId,
      isAddAnswer: false,
    }
    let res3 = await TransactionsOredrsCreate(data2)
    if (res3.success) {
      const data = qs.stringify({
        id: selectData.value.applyPaymentSettlementId,
        status: 5,
      });
      const res = await ApplyPaymentSettlementUpdatePaymentStatus(data);
      if (res.success) {
        const updataStatus = qs.stringify({
          id: selectData.value.applyPaymentSettlementId
        })
        let updataRes = await ApplyPaymentSettlementUpdateIsSettlement(updataStatus)
        getSupplierEnterpriseInfoGetAllByPagedAndSort()
      } else {
        ElMessage.error(res.msg)
      }
      ElMessage.success('完成余额支付！')
      emitter.emit('refreshMoney')
      payBalanceVisible.value = false
    } else {
      ElMessage.error(res3.msg)
    }
  }

  onMounted(() => {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  })

  function handleSizeChange() {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  }
  function handleCurrentChange() {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  }
  //点击放款操作
  return {
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    DialogVisible,
    rowData,
    handleApply,
    handelSupplierPay,
    payLeaveMoney,
    payData,
    handlePayData,
    selectRouteTypeVisible,
    routerTittle,
    saveApply,
    payBalanceVisible,
    handleLender,
    lenderVisible
  }
}

